package com.bblocks.redisqueue;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author yanmeng
 */
@Component
//@ConditionalOnProperty(name = "spring.redis.redisson.enabled", matchIfMissing = true)
@ConditionalOnBean(name = "redissonConfig")
public class RedisDelayedQueue {
	public static final String BB_DELAY_QUEUE_PRE = "BB_DELAY_QUEUE::";

    @Autowired
    RedissonClient redissonClient;

    private static Logger logger = LoggerFactory.getLogger(RedisDelayedQueue.class);

    /**
     * 添加队列
     *
     * @param t        DTO传输类
     * @param delay    时间数量
     * @param timeUnit 时间单位
     * @param <T>      泛型
     */
    public <T> void addQueue(T t, long delay, TimeUnit timeUnit, String queueName) {
        logger.info("添加队列{},delay:{},timeUnit:{},数据：{}",queueName, delay, timeUnit,t);
        RBlockingQueue<T> blockingFairQueue = redissonClient.getBlockingQueue(BB_DELAY_QUEUE_PRE + queueName);
        RDelayedQueue<T> delayedQueue = redissonClient.getDelayedQueue(blockingFairQueue);
        delayedQueue.offer(t, delay, timeUnit);
    }

	public <T> void addQueueSeconds(T t, long delay,   String queueName) {

		addQueue(t,delay,TimeUnit.SECONDS,queueName);
	}


	public <T> void addQueueTheTime(T t, Date noticeTime, String queueName) {
		long delay = DateUtil.between(new Date(),noticeTime, DateUnit.MINUTE);
		if(delay < 0L)
			delay = 0L;

		addQueue(t,delay,TimeUnit.SECONDS,queueName);
	}

}
